﻿
using PerpheralDevice;
using PerpheralDevice.IRepository;
using System.Collections.Concurrent;

namespace AppMachine.EntityFrameworkCore.Repositories.PerpDev;

/// <summary>
/// 外部设备仓储
/// </summary>
public class PerpDevRepository : AppFramework.DesignMode.Singleton<PerpDevRepository>, IPerpDevRepository {
    
    private readonly PerpDevConfigRepository mfPerpDevConfigRepository = new();
    private readonly ConcurrentDictionary<string, PerpheralDevice.PerpDev> _DicPerpDev = new();
    private PerpDevRepository() { }
    public T GetByID<T>(string devID) where T : PerpheralDevice.PerpDev {
        PerpheralDevice.PerpDev tempPerpDev = _DicPerpDev.GetOrAdd(devID, (tempComID) => {
            var tempConfig = mfPerpDevConfigRepository.Query(devID);
            Type? tempType = Type.GetType(tempConfig.DevType);
            if (tempType != null) {
                object? tempObject = Activator.CreateInstance(tempType, tempConfig.DevID, tempConfig.DevName, tempConfig.DevParamSerialized);
                if (tempObject is PerpheralDevice.PerpDev tempPerpDev) {
                    return tempPerpDev.CfgSet(this.mfPerpDevConfigRepository, tempConfig);
                }
            }
            return null;
        });

        return tempPerpDev as T;
    }

    public IEnumerable<T> GetAll<T>() where T : PerpheralDevice.PerpDev {
        mfPerpDevConfigRepository.GetAll().ToList().ForEach(tempPerpDev => {
            if (!this._DicPerpDev.ContainsKey(tempPerpDev.DevID)) {
                this.GetByID<T>(tempPerpDev.DevID);
            }
        });

       return this._DicPerpDev.Values.OfType<T>();
    }

    public T Update<T>(IPerpDevConfig perpDevConfig) where T : PerpheralDevice.PerpDev {

        throw new NotImplementedException();
    }

}
